@{
    ViewData["Titel"] = "验章";
}

<h2 style="margin:20px 0">验章</h2>
<hr />
<div class="layui-tab">
    <ul class="layui-tab-title">
        <li class="layui-this" id="ukey">UKEY验章</li>
        <!-- <li id='zs'>证书验章</li> -->
    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <div class="form-group">
                <div class="col-md-offset-1 col-md-10 ">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">选择验证的UKEY</label>
                            <div class="col-sm-10" style="line-height: 30px;">
                                <select id="userCertID" name="ukeySelect" class="form-control"></select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealName" class="col-sm-2 control-label">印章名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="sealName" readonly="readonly">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealType" class="col-sm-2 control-label">印章类型</label>
                            <div class="col-sm-10" id="typeValue ">
                                <select id="sealType" name="sealType" class="form-control" disabled="disabled">
                                    <option value="">请选择</option>
                                    <option value="1">单位印章</option>
                                    <option value="2">个人印章</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealStartTime" class="col-sm-2 control-label">印章生效时间</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="sealStartTime" readonly="readonly" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealEndTime" class="col-sm-2 control-label">印章作废时间</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="sealEndTime" readonly="readonly" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">印章图片</label>
                            <div class="col-md-10">
                                <img id="pic" src="" style="max-width: 100%; border: 1px solid gray;" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">制章人证书</label>
                            <div class="col-sm-10">
                                <a id="makerCertBase64">下载</a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">印章绑定证书</label>
                            <div class="col-sm-10">
                                <a id="userCertBase64">下载</a>
                            </div>
                        </div>
                        <input type="hidden" id="sealBase64" />
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input id="btnCreate" type="button" value="验证印章" class="btn btn-default" />
                            </div>
                        </div>
                    </form>
                    <dl id="infoDiv" class="dl-horizontal" style="display: none"></dl>
                </div>
            </div>
        </div>
		
		<input type="hidden" id="yz" value=""/>
       <!-- <div class="layui-tab-item">
            <div class="form-group">
                <div class="col-md-offset-1 col-md-10 ">
                    <form class="form-horizontal">
                        <div class="form-group " id="cer">
                            <label class="col-sm-2 control-label">用户印章</label>
                            <div class="col-sm-10" style="line-height: 30px;">
                                <button type="button" class="btn btn-default" id="ImportConfig">点击上传印章</button>
                                <span id="filename"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealName" class="col-sm-2 control-label">印章名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="cer_sealName" readonly="readonly">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealType" class="col-sm-2 control-label">印章类型</label>
                            <div class="col-sm-10" id="typeValue ">
                                <select id="cer_sealType" name="sealType" class="form-control" disabled="disabled">
                                    <option value="">请选择</option>
                                    <option value="1">单位印章</option>
                                    <option value="2">个人印章</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealStartTime" class="col-sm-2 control-label">印章生效时间</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="cer_sealStartTime" readonly="readonly" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealEndTime" class="col-sm-2 control-label">印章作废时间</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="cer_sealEndTime" readonly="readonly" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">印章图片</label>
                            <div class="col-md-10">
                                <img id="cer_pic" src="" style="max-width: 100%; border: 1px solid gray;" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">制章人证书</label>
                            <div class="col-sm-10">
                                <a id="cer_makerCertBase64">下载</a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">印章绑定证书</label>
                            <div class="col-sm-10">
                                <a id="cer_userCertBase64">下载</a>
                            </div>
                        </div>
                        <input type="hidden" id="cer_sealBase64" />
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input id="cer_btnCreate" type="button" value="验证印章" class="btn btn-default" />
                            </div>
                        </div>
                    </form>
                    <dl id="cer_infoDiv" class="dl-horizontal" style="display: none"></dl>
                </div>
            </div>
        </div> -->
    </div>
</div>














@*<div class="form-group">
    <div class="col-md-offset-1 col-md-10 ">
        <form class="form-horizontal">
            <div class="form-group">
                <label class="col-sm-2 control-label">选择验证的UKEY</label>
                <div class="col-sm-10" style="line-height: 30px;">
                    <select id="userCertID" name="ukeySelect" class="form-control"></select>
                </div>
            </div>
            <div class="form-group">
                <label for="sealName" class="col-sm-2 control-label">印章名称</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="sealName" readonly="readonly">
                </div>
            </div>
            <div class="form-group">
                <label for="sealType" class="col-sm-2 control-label">印章类型</label>
                <div class="col-sm-10" id="typeValue ">
                    <select id="sealType" name="sealType" class="form-control" disabled="disabled">
                        <option value="">请选择</option>
                        <option value="1">单位印章</option>
                        <option value="2">个人印章</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="sealStartTime" class="col-sm-2 control-label">印章生效时间</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="sealStartTime" readonly="readonly" />
                </div>
            </div>
            <div class="form-group">
                <label for="sealEndTime" class="col-sm-2 control-label">印章作废时间</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="sealEndTime" readonly="readonly" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-2">印章图片</label>
                <div class="col-md-10">
                    <img id="pic" src="" style="max-width: 100%; border: 1px solid gray;" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">制章人证书</label>
                <div class="col-sm-10">
                    <a id="makerCertBase64">下载</a>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">印章绑定证书</label>
                <div class="col-sm-10">
                    <a id="userCertBase64">下载</a>
                </div>
            </div>
            <input type="hidden" id="sealBase64" />
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input id="btnCreate" type="button" value="验证印章" class="btn btn-default" />
                </div>
            </div>
        </form>
        <dl id="infoDiv" class="dl-horizontal" style="display: none"></dl>
    </div>
</div>*@

<div id="layerPagePinCode" style="display: none">
    <div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">
        请输入制章人PIN码：<br />
        <input type="password" name="ukeyPinCode" class="form-control" />
        <span id="pinError"></span>
    </div>
</div>


@section scripts {
    <script src="/Content/layui/layui.js" charset="utf-8"></script>
    <script src="~/js/dateformat.js"></script>
    <script>
        function EnumKey(funcBack, errorCallBack) {
            var socket = new WebSocket("ws://127.0.0.1:2012/CertInfo");
            try {
                socket.onerror = errorCallBack;
                socket.onopen = function (msg) {

                    //alert("连接成功！");
                    socket.send("abc");
                };
                socket.onmessage = function (e) {
                    if (isNumber(e.data)) {
                        funcBack("");
                    } else {
                        //alert(e.data);
                        funcBack(e.data);
                    }
                };
            }
            catch (ex) {
                funcBack("");
            }
        }
        function GetCertAndSeal(certSN, funcBack) {
            //alert(certSN);
            var dtd = $.Deferred();
            var socket = new WebSocket("ws://127.0.0.1:2012/SealAndCertBase64");
            try {
                socket.onopen = function (msg) {
                    //alert("连接成功！");
                    socket.send(certSN);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                    dtd.resolve();
                };
            } catch (ex) {
                funcBack("");
                socket.close();
            } finally {
                return dtd.promise();
            }
        }

        function initlist(str) {
            $("select[name='ukeySelect']").each(function (index, element) {
                if (str == "") {
                    $(element).empty();
                }
                var certList = $.parseJSON(str);
                var selObj = $(element);
                var maxIndex = $(element).find("option:last").index(); //获取Select最大的索引值
                //alert(maxIndex);
                for (var i = maxIndex; i >= 0; i--) {
                    //alert(i);
                    var exsitFlag = false;
                    var currentValue = $(element).find("option:eq(" + i + ")").val();
                    for (var j = 0; j < certList.CertInfolist.length; j++) {
                        if (currentValue == certList.CertInfolist[j].CertID) {
                            exsitFlag = true;
                            break;
                        }
                    }
                    if (exsitFlag == false) {
                        $(element).find("option:eq(" + i + ")").remove();
                    }
                }
                for (var i = 0; i < certList.CertInfolist.length; i++) {
                    if ($(element).find("option[value='" + certList.CertInfolist[i].CertID + "']").index() == -1) {
                        selObj.append("<option value='" + certList.CertInfolist[i].CertID + "'>" + certList.CertInfolist[i].CertCN + "</option>");
                    }
                }

            });
        }
        function myPost(url, args) {
            var body = $(document.body),
                form = $("<form method='post'></form>"),
                input;
            form.attr({ "action": url });
            $.each(args, function (key, value) {
                input = $("<input type='hidden'>");
                input.attr({ "name": key });
                input.val(value);
                form.append(input);
            });

            form.appendTo(document.body);
            form.submit();
            document.body.removeChild(form[0]);
        }
        function isNumber(val) {

            var regPos = /^\d+(\.\d+)?$/; //非负浮点数
            var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
            if (regPos.test(val) || regNeg.test(val)) {
                return true;
            } else {
                return false;
            }
        }
        function DisplayMessage(message) {
            var mydate = new Date();
            $("#infoDiv").append("<dt>" +
                mydate.Format("hh:mm:ss") +
                "</dt><dd>" +
                message +
                "</dd>");
        }
        function cer_DisplayMessage(message) {
            var mydate = new Date();
            $("#cer_infoDiv").append("<dt>" +
                mydate.Format("hh:mm:ss") +
                "</dt><dd>" +
                message +
                "</dd>");
        }

        //计算印章哈希

        function ComputeSealHash() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/ComputeSealHash";
            var socket = new WebSocket(uri);
            // 建立 web socket 连接成功触发事件
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    makerCertID: $("#makerCertID").val(),
                    userCertID: $("#userCertID").val(),
                    picBase64: $("#picBase64").val(),
                    sealName: $("#sealName").val(),
                    sealType: $("#sealType").val(),
                    sealStartTime: $("#sealStartTime").val(),
                    sealEndTime: $("#sealEndTime").val()
                };
                // 使用 send() 方法发送数据
                socket.send(JSON.stringify(data));
            };
            // 断开 web socket 连接成功触发事件
            socket.onclose = function (e) { console.log("closed"); };
            // 接收服务端数据时触发事件socket.close();
            socket.onmessage = function (e) {
                console.log(e.data);
                var retJSONObject = JSON.parse(e.data);
                if (retJSONObject.error == "Ok") {
                    $("#sealBase64").val(retJSONObject.sealBase64);
                    $("#sealHashBase64").val(retJSONObject.digestBase64);
                    dtd.resolve(e.data);
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        //计算印章签名
        function ComputeSealSig() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/SignDataEx";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    certId: $("#makerCertID").val(),
                    hashBase64: $("#sealHashBase64").val(),
                    strPin: "111111"
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                var retJSONObject = JSON.parse(e.data);
                if (retJSONObject.error == "Ok") {
                    $("#sealSigBase64").val(retJSONObject.SigBase64);
                    dtd.resolve(e.data);
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        //计算最终印章数据
        function ComputeSeal() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/ComputeSeal";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    sealWithoutSigBase64: $("#sealBase64").val(),
                    sigBase64: $("#sealSigBase64").val()
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                var retJSONObject = JSON.parse(e.data);
                if (retJSONObject.error == "Ok") {
                    $("#sealBase64").val(retJSONObject.sealBase64);
                    dtd.resolve(e.data);
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        //写入印章数据
        function WriteUkey() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/WriteUkey";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    certID: $("#userCertID").val(),
                    fileName: "GBESEAL",
                    dataBase64: $("#sealBase64").val()
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                if (e.data == "Ok") {
                    dtd.resolve(e.data);
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        function ReadUkey() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/ReadUkey";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    certID: $("#userCertID").val(),
                    fileName: "GBESEAL"
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                var retJSONObject = JSON.parse(e.data);
                console.log(1);
                console.log(retJSONObject);
                if (retJSONObject.error == "Ok") {
                    $("#sealBase64").val(retJSONObject.dataBase64);
                    dtd.resolve(e.data);
                } else {
                    DisplayMessage("文件读取失败");
                    $("#btnCreate").attr("disabled", false);
                    return;
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }

        function GetSealInfo() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/GetSealInfo";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    sealBase64: $("#sealBase64").val()
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(2);
                console.log(JSON.parse(e.data));
                socket.close();
                dtd.resolve(e.data);
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        function cer_GetSealInfo(result) {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/GetSealInfo";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    sealBase64: result
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                socket.close();
                dtd.resolve(e.data);
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        function VerifySealData() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/VerifySealData";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    sealBase64: $("#sealBase64").val()
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(3);
                console.log(e.data);
                socket.close();
                dtd.resolve(e.data);
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        function cer_VerifySealData(result) {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/VerifySealData";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    sealBase64: result
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                socket.close();
                dtd.resolve(e.data);
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        function base64toBlob(b64Data, contentType, sliceSize) {
            contentType = contentType || '';
            sliceSize = sliceSize || 512;
            var byteCharacters = atob(b64Data);
            var byteArrays = [];
            for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                var slice = byteCharacters.slice(offset, offset + sliceSize);
                var byteNumbers = new Array(slice.length);
                for (var i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                }
                var byteArray = new Uint8Array(byteNumbers);
                byteArrays.push(byteArray);
            }
            var blob = new Blob(byteArrays, { type: contentType });
            return blob;
        }
        /*
          通用的打开下载对话框方法，没有测试过具体兼容性
          url 下载地址，也可以是一个blob对象，必选
          saveName 保存文件名，可选
        */
        function openDownloadDialog(url, saveName) {
            if (typeof url == 'object' && url instanceof Blob) {
                url = URL.createObjectURL(url); // 创建blob地址
            }
            var aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
            var event;
            if (window.MouseEvent) event = new MouseEvent('click');
            else {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            aLink.dispatchEvent(event);
        }
        //Base64编码
        function Base64() {
        	// private property
        	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        
        	// public method for encoding
        	this.encode = function(input) {
        		var output = "";
        		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        		var i = 0;
        		input = _utf8_encode(input);
        		while (i < input.length) {
        			chr1 = input.charCodeAt(i++);
        			chr2 = input.charCodeAt(i++);
        			chr3 = input.charCodeAt(i++);
        			enc1 = chr1 >> 2;
        			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        			enc4 = chr3 & 63;
        			if (isNaN(chr2)) {
        				enc3 = enc4 = 64;
        			} else if (isNaN(chr3)) {
        				enc4 = 64;
        			}
        			output = output +
        				_keyStr.charAt(enc1) +
        				_keyStr.charAt(enc2) +
        				_keyStr.charAt(enc3) +
        				_keyStr.charAt(enc4);
        		}
        		return output;
        	};
        
        	// public method for decoding
        	this.decode = function(input) {
        		var output = "";
        		var chr1, chr2, chr3;
        		var enc1, enc2, enc3, enc4;
        		var i = 0;
        		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        		while (i < input.length) {
        			enc1 = _keyStr.indexOf(input.charAt(i++));
        			enc2 = _keyStr.indexOf(input.charAt(i++));
        			enc3 = _keyStr.indexOf(input.charAt(i++));
        			enc4 = _keyStr.indexOf(input.charAt(i++));
        			chr1 = (enc1 << 2) | (enc2 >> 4);
        			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        			chr3 = ((enc3 & 3) << 6) | enc4;
        			output = output + String.fromCharCode(chr1);
        			if (enc3 != 64) {
        				output = output + String.fromCharCode(chr2);
        			}
        			if (enc4 != 64) {
        				output = output + String.fromCharCode(chr3);
        			}
        		}
        		output = _utf8_decode(output);
        		return output;
        	};
        
        	// private method for UTF-8 encoding
        	_utf8_encode = function(string) {
        		string = string.replace(/\r\n/g, "\n");
        		var utftext = "";
        		for (var n = 0; n < string.length; n++) {
        			var c = string.charCodeAt(n);
        			if (c < 128) {
        				utftext += String.fromCharCode(c);
        			} else if ((c > 127) && (c < 2048)) {
        				utftext += String.fromCharCode((c >> 6) | 192);
        				utftext += String.fromCharCode((c & 63) | 128);
        			} else {
        				utftext += String.fromCharCode((c >> 12) | 224);
        				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        				utftext += String.fromCharCode((c & 63) | 128);
        			}
        
        		}
        		return utftext;
        	};
        
        	// private method for UTF-8 decoding
        	_utf8_decode = function(utftext) {
        		var string = "";
        		var i = 0;
        		var c = c1 = c2 = 0;
        		while (i < utftext.length) {
        			c = utftext.charCodeAt(i);
        			if (c < 128) {
        				string += String.fromCharCode(c);
        				i++;
        			} else if ((c > 191) && (c < 224)) {
        				c2 = utftext.charCodeAt(i + 1);
        				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        				i += 2;
        			} else {
        				c2 = utftext.charCodeAt(i + 1);
        				c3 = utftext.charCodeAt(i + 2);
        				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        				i += 3;
        			}
        		}
        		return string;
        	};
        }
        
		//外部加密
        function ExternalEncrypt(Json, funcBack) {
        	console.log(Json)
        	var socket = new WebSocket("ws://127.0.0.1:2012/CustomizeEnvelope");
        	try {
        
        		socket.onopen = function(msg) {
        			socket.send(Json);
        		};
        		socket.onmessage = function(e) {
        			console.log(e.data, "加密");
        			funcBack(e.data);
        			socket.close();
        		};
        	} catch (ex) {
        		funcBack("");
        		socket.close();
        	}
        
        }
        
        function EncryptCertList(back) {
        	var socket = new WebSocket("ws://127.0.0.1:2012/EncryptCertList");
        	try {
        
        		socket.onopen = function(msg) {
        			socket.send("1");
        		};
        		socket.onmessage = function(e) {
        			back(e.data);
        			socket.close();
        		};
        	} catch (ex) {
        		funcBack("");
        		socket.close();
        	}
        }
        //layui.use('layer',
        //    function () {
        //        layer = layui.layer;
        //    });
        $(function () {
			$.ajax({
			    url: "/InfoLog/ReturnValidateCode",
			    type: 'get',
			
			    success: function (data) {
			        $("#yz").val(data.validateCode);
			    },
			});
				var ValidateCode = null;
            var layer = null;
            var cer_SealInfo = '';
            layui.use(['upload', 'layer', 'element'], function () {
                var upload = layui.upload;
                var element = layui.element;
                layer = layui.layer;
                //执行实例
                upload.render({
                    elem: '#ImportConfig'
                    , url: '/api/upload/'
                    , auto: false //选择文件后不自动上传
                    , accept: 'file'
                    , multiple: false
                    //, bindAction: '#testListAction' //指向一个按钮触发上传
                    , choose: function (obj) {
                        var files = obj.pushFile();
                        obj.preview(function (index, file, result) {
                            console.log(result);
                            cer_SealInfo = result.substr(result.indexOf(",") + 1);
                            console.log(cer_SealInfo);
                            $("#filename").html(file.name);
                        });
                    }
                });
            });
			
			
			$("#ukey").click(() => {
				var a = '@ViewData["ValidateCode"]';
				$.ajax({
					url: "/InfoLog/ReturnValidateCode",
					type: 'get',
			
					success: function(data) {
						console.log(data);
						console.log(a,"ukey")
					},
					error:()=>{
						console.log("ukey错误")
					}
				});
			
			});
			// $("#zs").click(() => {
			// 	var a = '@ViewData["ValidateCode"]';
			// 	$.ajax({
			// 		url: "/InfoLog/ReturnValidateCode?t="+new Date(),
			// 		type: 'get',
			// 	
			// 		success: function(data) {
			// 			console.log(data);
			// 			console.log(a,"证书")
			// 		},
			// 		error:()=>{
			// 			console.log("证书错误")
			// 		}
			// 	});
			// });
            //***********************************************************************************
            EnumKey(function (data) {
                initlist(data);
            },
                function () {
                    layer.alert("未安装UKEY支持服务！");
                });
            $('#btnCreate').click(function () {
				var base64 = new Base64();
                $("#infoDiv").empty();
                $("#infoDiv").fadeIn();
                $("#btnCreate").attr("disabled", true);
                DisplayMessage("正在获取UKEY证书");
                console.log($("#userCertID").val());
                var userCertBase64 = "";
                var certUserSN = $("#userCertID").val();
                var dtd2 = GetCertAndSeal(certUserSN, function (certAndSeal) {
                    var certAndSealJObject = JSON.parse(certAndSeal);
                    console.log(1111);
                    console.log(certAndSealJObject);
                    if (certAndSealJObject.CertBase64.length != 0) {
                        userCertBase64 = certAndSealJObject.CertBase64;
                    }

                });
                DisplayMessage("正在读取印章");
                var dtd = $.Deferred();
                $.when(dtd2).done(function () {
                    ReadUkey().done(function () {
                        GetSealInfo().done(function (ret) {
                            var sealInfo = JSON.parse(ret);
                            console.log(222222222);
                            console.log(sealInfo);
                            $("#sealName").val(sealInfo.sealName);
                            $("#sealType").val(sealInfo.sealType);
                            $("#sealStartTime").val(sealInfo.startTime);
                            $("#sealEndTime").val(sealInfo.endTime);
                            $("#makerCertBase64").unbind("click");
                            $("#makerCertBase64").click(function () {
                                var blob = base64toBlob(sealInfo.makerCertBase64, "application/x-x509-ca-cert");
                                openDownloadDialog(blob, "makerCert.cer");
                            });
                            $("#userCertBase64").unbind("click");
                            $("#userCertBase64").click(function () {
                                var blob = base64toBlob(sealInfo.userCertBase64, "application/x-x509-ca-cert");
                                openDownloadDialog(blob, "userCert.cer");
                            });
                            $("#pic").attr("src", "data:image/png;base64," + sealInfo.picBase64);
                            VerifySealData().done(function (ret) {
                                var retObject = JSON.parse(ret);
                                if (retObject.error == "Ok") {
                                    DisplayMessage("印章合法");
                                } else {
                                    DisplayMessage("印章验证错误");
                                   
                                    var errorCode = parseInt(retObject.error.slice(retObject.error.indexOf(":") + 1));
                                    console.log(errorCode);
                                    switch (errorCode) {
                                        case -0xc0101:
                                            DisplayMessage("无法解析的签章结构");
                                            break;
                                        case -0xc0102:
                                            DisplayMessage("BIO读取错误");
                                            break;
                                        case -0xc0103:
                                            DisplayMessage("制章人证书结构解析失败");
                                            break;
                                        case -0xc0104:
                                            DisplayMessage("PCC为空");
                                            break;
                                        case -0xc0105:
                                            DisplayMessage("装填公钥失败");
                                            break;
                                        case -0xc0106:
                                            DisplayMessage("签名验证失败");
                                            break;
                                        case -0xc0107:
                                            DisplayMessage("制作时间不在印章有效期内");
                                            break;
                                        case -0xc0108:
                                            DisplayMessage("印章已过期");
                                            break;
                                        case -0xc0109:
                                            DisplayMessage("用户证书结构解析失败");
                                            break;
                                        case -0xc010a:
                                            DisplayMessage("根证书储存区初始化失败");
                                            break;
                                        case -0xc010b:
                                            DisplayMessage("验证根证书或CRL失败");
                                            break;
                                        case -0xc010c:
                                            DisplayMessage("制章人证书不在有效期内");
                                            break;
                                        default:
                                            break;
                                    }
                                    $("#btnCreate").attr("disabled", false);
                                }
                                dtd.resolve();
                            });
                        });
                    });
                });
                dtd.done(function () {
					EncryptCertList((data) => {
						data = JSON.parse(data);
						let CertID = null;
						//获取选中的ID值
						$(data.CertInfolist).each((i, value) => {
							if (value.CertCN == $("#userCertID option:selected").text()) {
								CertID = value.CertID;
								return;
							}
						})
						var str = JSON.stringify({
							arrayNo: $("#userCertID").val(),
							ValidateCode:$("#yz").val()
						});
						var External = {
							CertID: CertID,
							//编码
							DataBase64: base64.encode(str)
						};
						ExternalEncrypt(JSON.stringify(External), (data) => {
							data = JSON.parse(data);
							if (data.error == "Ok") {
								var data = {
									// ArrayNo: CertID,
									EncryptData: data.contentBase64
								};
								 $.post("/ProduceSign/Verify",data,(data)=>{
									 DisplayMessage(data.message);
								 });
								$("#btnCreate").attr("disabled", false);
								
								
								
							}
						});
					})
                   
                });


            });
            // 证书验章
//             $('#cer_btnCreate').click(function () {
//                 console.log(111);
//                 $("#cer_infoDiv").empty();
//                 $("#cer_infoDiv").fadeIn();
//                 $("#cer_btnCreate").attr("disabled", true);
//                 if (cer_SealInfo == '') {
//                     console.log(2222);
//                     $("#cer_btnCreate").attr("disabled", false);
//                     return;
//                 } 
//                 //DisplayMessage("正在获取UKEY证书");
//                 //console.log($("#cer_userCertID").val());
//                 //var userCertBase64 = "";
//                 //var certUserSN = $("#cer_userCertID").val();
//                 //var dtd2 = GetCertAndSeal(certUserSN, function (certAndSeal) {
//                 //    var certAndSealJObject = JSON.parse(certAndSeal);
//                 //    if (certAndSealJObject.CertBase64.length != 0) {
//                 //        userCertBase64 = certAndSealJObject.CertBase64;
//                 //    }
//                 //});
//                 //DisplayMessage("正在读取印章");
//                 var dtd = $.Deferred();
//                 //$.when(dtd2).done(function () {
//                 //    ReadUkey().done(function () {
//                 cer_GetSealInfo(cer_SealInfo).done(function (ret) {
//                     var sealInfo = JSON.parse(ret);
//                     console.log(sealInfo);
//                             $("#cer_sealName").val(sealInfo.sealName);
//                             $("#cer_sealType").val(sealInfo.sealType);
//                             $("#cer_sealStartTime").val(sealInfo.startTime);
//                             $("#cer_sealEndTime").val(sealInfo.endTime);
//                             $("#cer_makerCertBase64").unbind("click");
//                             $("#cer_makerCertBase64").click(function () {
//                                 var blob = base64toBlob(sealInfo.makerCertBase64, "application/x-x509-ca-cert");
//                                 openDownloadDialog(blob, "makerCert.cer");
//                             });
//                             $("#cer_userCertBase64").unbind("click");
//                             $("#cer_userCertBase64").click(function () {
//                                 var blob = base64toBlob(sealInfo.userCertBase64, "application/x-x509-ca-cert");
//                                 openDownloadDialog(blob, "userCert.cer");
//                             });
//                             $("#cer_pic").attr("src", "data:image/png;base64," + sealInfo.picBase64);
//                             cer_VerifySealData(cer_SealInfo).done(function (ret) {
//                                 var retObject = JSON.parse(ret);
//                                 if (retObject.error == "Ok") {
//                                     cer_DisplayMessage("印章合法");
//                                 } else {
//                                     cer_DisplayMessage("印章验证错误");
//                                     var errorCode = parseInt(retObject.error.slice(retObject.error.indexOf(":") + 1));
//                                     console.log(errorCode);
//                                     switch (errorCode) {
//                                         case -0xc0101:
//                                             cer_DisplayMessage("无法解析的签章结构");
//                                             break;
//                                         case -0xc0102:
//                                             cer_DisplayMessage("BIO读取错误");
//                                             break;
//                                         case -0xc0103:
//                                             cer_DisplayMessage("制章人证书结构解析失败");
//                                             break;
//                                         case -0xc0104:
//                                             cer_DisplayMessage("PCC为空");
//                                             break;
//                                         case -0xc0105:
//                                             cer_DisplayMessage("装填公钥失败");
//                                             break;
//                                         case -0xc0106:
//                                             cer_DisplayMessage("签名验证失败");
//                                             break;
//                                         case -0xc0107:
//                                             cer_DisplayMessage("制作时间不在印章有效期内");
//                                             break;
//                                         case -0xc0108:
//                                             cer_DisplayMessage("印章已过期");
//                                             break;
//                                         case -0xc0109:
//                                             cer_DisplayMessage("用户证书结构解析失败");
//                                             break;
//                                         case -0xc010a:
//                                             cer_DisplayMessage("根证书储存区初始化失败");
//                                             break;
//                                         case -0xc010b:
//                                             cer_DisplayMessage("验证根证书或CRL失败");
//                                             break;
//                                         case -0xc010c:
//                                             cer_DisplayMessage("制章人证书不在有效期内");
//                                             break;
//                                         default:
//                                             break;
//                                     }
//                                 }
//                                 dtd.resolve();
//                             });
//                         });
//                 //    });
//                 //});
//                 dtd.done(function () {
// 					EncryptCertList((data) => {
// 						data = JSON.parse(data);
// 						let CertID = data.CertInfolist[0].CertID;
// 						var str = JSON.stringify({
// 							arrayNo: $("#cer_userCertID").val()
// 						});
// 						var External = {
// 							CertID: CertID,
// 							//编码
// 							DataBase64: base64.encode(str)
// 						};
// 						ExternalEncrypt(JSON.stringify(External), (data) => {
// 							data = JSON.parse(data);
// 							if (data.error == "Ok") {
// 								var data = {
// 									// ArrayNo: CertID,
// 									EncryptData: data.contentBase64
// 								};
// 								 $.post("/ProduceSign/Verify",data);
// 								$("#cer_btnCreate").attr("disabled", false);
// 								DisplayMessage("印章验证完成");
// 							}
// 						});
// 					})
//                    
//                 });
// 
// 
//             });
        });
    </script>
}
